package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Visitor;
import com.itheima.domain.vo.VisitorVo;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheimma.service.db.UserInfoService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class VisitorManager {

    @DubboReference
    private VisitorService visitorService;

    @DubboReference
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //查询访客
    public ResponseEntity findVisitorByCondition(){
        Long userId = UserHolder.get().getId();
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        //要把该定义放在if判断之外，才能被识别
        ArrayList<VisitorVo> visitorVos = new ArrayList<>();

        //要判断是否访客时间为空
        if (StrUtil.isNotEmpty(lastAccessTime)) {
            //获取访客记录
            List<Visitor> visitors = visitorService.findVisitorByCondition(userId, Long.parseLong(lastAccessTime));

            //封装vo
            if (CollectionUtil.isNotEmpty(visitors)) {
                for (Visitor visitor : visitors) {
                    UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());
                    VisitorVo vo = new VisitorVo();
                    vo.setUserInfo(userInfo);
                    vo.setFateValue(visitor.getScore().longValue());
                    visitorVos.add(vo);
                }
            }
        }
        //设置访问时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId , String.valueOf(System.currentTimeMillis()));

        return ResponseEntity.ok(visitorVos);

    }

}
